<script setup lang="ts">
import { ref, computed } from 'vue';
import type { User, CreateUserRequest, UpdateUserRequest } from '@/api/endpoints/system/user';
import { createUser, updateUser } from '@/api/endpoints/system/user';
import { showSuccess } from '@/lib/toast';
import { DynamicForm, createUserFormSchema, editUserFormSchema } from '@/components/form';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';

type FormMode = 'create' | 'edit';

interface Props {
  open: boolean;
  mode: FormMode;
  user?: User | null;
}

const props = withDefaults(defineProps<Props>(), {
  user: null,
});

const emit = defineEmits<{
  close: [];
  success: [];
}>();

const loading = ref(false);

// 根据模式选择 schema
const schema = computed(() => {
  return props.mode === 'create' ? createUserFormSchema : editUserFormSchema;
});

// 计算初始值
const initialValues = computed(() => {
  if (props.mode === 'edit' && props.user) {
    return {
      id: props.user.id,
      name: props.user.name,
      email: props.user.email,
      position: props.user.position || '',
      phone: props.user.phone || '',
      gender: props.user.gender,
      status: props.user.status,
      bio: props.user.bio || '',
      role: props.user.role || '',
    };
  }
  return undefined;
});

// 计算对话框标题和描述
const dialogTitle = computed(() => {
  return props.mode === 'create' ? '创建用户' : '编辑用户';
});

const dialogDescription = computed(() => {
  return props.mode === 'create'
    ? '填写用户信息来创建新用户。点击保存按钮完成创建。'
    : '修改用户信息。点击保存按钮完成更新。';
});

// 计算提交按钮文本
const submitButtonText = computed(() => {
  return props.mode === 'create' ? '创建' : '更新';
});

// 处理表单提交
async function handleSubmit(values: Record<string, any>) {
  try {
    loading.value = true;

    if (props.mode === 'create') {
      await createUser(values as CreateUserRequest);
      showSuccess('用户创建成功');
    } else {
      await updateUser(values as UpdateUserRequest);
      showSuccess('用户更新成功');
    }

    emit('success');
    handleClose();
  } catch (error) {
    console.error('操作失败:', error);
  } finally {
    loading.value = false;
  }
}

// 处理取消
function handleCancel() {
  handleClose();
}

// 处理关闭
function handleClose() {
  emit('close');
}
</script>

<template>
  <Dialog :open="props.open" @update:open="handleClose">
    <DialogContent>
      <DialogHeader>
        <DialogTitle>{{ dialogTitle }}</DialogTitle>
        <DialogDescription>{{ dialogDescription }}</DialogDescription>
      </DialogHeader>

      <DynamicForm
        :schema="schema"
        :initial-values="initialValues"
        :loading="loading"
        :submit-button-text="submitButtonText"
        @submit="handleSubmit"
        @cancel="handleCancel"
      />
    </DialogContent>
  </Dialog>
</template>
